/*
 * Android Simple Music player
   Copyright hayoon.ko (shauku@naver.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package kr.ac.kaist.simplemusicplayer;

import java.io.FileNotFoundException;
import java.io.InputStream;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


/**
 * Music Control Activity - displays 1. album cover if exist, 2. title of song 3. control button (pause/FF/RW/Stop) 4. ToList button 
 * @author shauku@naver.com
 * @version 10
 *
 */
public class MusicControl extends Activity{
	
	/*use Bind to communicate with Service class*/
    private SMPInterface smpInterface;

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.controls);

    		startService(new Intent(MusicControl.this, SMPService.class));            
            bindService(new Intent(MusicControl.this, SMPService.class),mConnection,0);
                       
 
            /*create pause button*/
            Button pauseBtn = (Button) findViewById(R.id.pause);
            pauseBtn.setOnClickListener(new OnClickListener(){
            	public void onClick(View v){
    				try{
    					smpInterface.pause();
    					updateAlbumTitle();
    					updateAlbumImage();
    				}catch(Exception  e){
        	   			Log.e(getString(R.string.app_name), e.getMessage());                		
                	}
            	}
            });    

            /*create RW button*/
            Button skipBackBtn = (Button) findViewById(R.id.skipb);
            skipBackBtn.setOnClickListener(new OnClickListener(){
            	public void onClick(View v){
    				try{
    					smpInterface.skipBack();
    					updateAlbumImage();
    					updateAlbumTitle();
    					}catch(Exception  e){
    	    	   			Log.e(getString(R.string.app_name), e.getMessage());                		
    	            	}
            	}
            });    

            /*create FF button*/
            Button skipFwdBtn = (Button) findViewById(R.id.skipf);
            skipFwdBtn.setOnClickListener(new OnClickListener(){
            	public void onClick(View v){
    				try{
    					smpInterface.skipForward();
    					updateAlbumImage();
    					updateAlbumTitle();
    				}catch(Exception  e){
        	   			Log.e(getString(R.string.app_name), e.getMessage());                		
                	}
            	}
            });    

            /*create STOP button*/
            Button stopBtn = (Button) findViewById(R.id.stop);
            stopBtn.setOnClickListener(new OnClickListener(){
            	public void onClick(View v){
    				try{
    					smpInterface.stop();
    					updateAlbumImage();
    					updateAlbumTitle();
    				}catch(Exception  e){
        	   			Log.e(getString(R.string.app_name), e.getMessage());                		
                	}
            	}
            });    

            
            /**
             * create ToList button - this invokes intent to start Music controller activity
             */            
            Button tolistBtn = (Button) findViewById(R.id.tolist);
            tolistBtn.setOnClickListener(new OnClickListener(){
            	public void onClick(View v){
            		Intent intent = new Intent(getApplicationContext(),MusicList.class);
            		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            		startActivity(intent);
            	}
            });       
    }  
    
    public void onDestroy(){
    	super.onDestroy();
		unbindService(mConnection);
    }
    
	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			smpInterface = SMPInterface.Stub.asInterface((IBinder) service);
			
			updateAlbumImage();
			updateAlbumTitle();
		}

		public void onServiceDisconnected(ComponentName className) {
			smpInterface = null;
		}
	};    

	/**
	  * get album art with bitmap format and change it to imageview content
	  * if image does not exist, it displays default png image
	  */	
	private void updateAlbumImage(){
		
		ImageView albumArt_view = null;
		
		try{
			if(false == smpInterface.isPlayerStopped())
			{
				String albumId = smpInterface.getCurrentSongId();
	
				 Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
				 Uri uri = ContentUris.withAppendedId(sArtworkUri, Integer.valueOf(albumId));
				 ContentResolver res = getContentResolver();				

				 InputStream in;
		          try {
		              in = res.openInputStream(uri);
		          	  Bitmap artwork = BitmapFactory.decodeStream(in);	
//				      Bitmap temp_art = Bitmap.createScaledBitmap(artwork, 50, 50, true);
				      
				      albumArt_view = (ImageView)findViewById(R.id.album_art_control);
				      albumArt_view.setImageBitmap(artwork);
		          } catch (FileNotFoundException e) {
		                  e.printStackTrace();
				      albumArt_view = (ImageView)findViewById(R.id.album_art_control);
				      albumArt_view.setImageResource(R.drawable.albumart_unknown);		                  
		              }     		          	  
				//update song image 
			}
			else  //music stopped
			{
			      albumArt_view = (ImageView)findViewById(R.id.album_art_control);
			      albumArt_view.setImageResource(R.drawable.albumart_unknown);					
			}
		}catch(Exception  e){
				Log.e(getString(R.string.app_name), e.getMessage());                		
		}	
	}

	/**
	  * get title info from service and display title in textview 
	  * if title not exist, it displays default "UNKNOWN" string
	  */	
	private void updateAlbumTitle(){
		
		TextView albumTitle = null;
		try{
			if(false == smpInterface.isPlayerStopped())
			{
				String title = smpInterface.getCurrentSongTitle();
	
				albumTitle = (TextView)findViewById(R.id.musictitle);
			    albumTitle.setText(title);				
			}
			else  //music stopped
			{
				  albumTitle = (TextView)findViewById(R.id.musictitle);
			      albumTitle.setText("Unknown");				
			}
		}catch(Exception  e){
				Log.e(getString(R.string.app_name), e.getMessage());                		
		}	
	}
	
}
///